package cn.pxs.config;

import cn.pxs.entity.User;
import cn.pxs.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableWebSecurity
public class MyWebConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                User user = userService.findByUsername(username);
                return user;
            }
        });
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/img/**");
        web.ignoring().antMatchers("/templates/**");
        //解决服务注册url被拦截的问题
        web.ignoring().antMatchers("/resources/**");
    }

    //Http 请求安全处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/api/public/goLogin")       //登录页面
                .loginProcessingUrl("/doLogin") // 登录页面的请求
                //登录 成功 的 处理
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req,
                                                        HttpServletResponse resp,
                                                        Authentication auth) throws IOException, ServletException {
                        System.out.println("登录成功:"+auth);
                        Object principal = auth.getPrincipal();
                        System.out.println("登录的账号是"+auth.getAuthorities());
                        Map map = new HashMap();
                        map.put("action","/api/public/goIndex");
                        String s = objectMapper.writeValueAsString(map);
                        resp.getWriter().write(s);
                        resp.getWriter().flush();
                        resp.getWriter().close();
                    }
                })
                //登录失败
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req,
                                                        HttpServletResponse resp,
                                                        AuthenticationException exception) throws IOException, ServletException {
                        Map map = new HashMap();
                        map.put("action","/api/public/goIndex");
                        map.put("stu",400);
                        String s = objectMapper.writeValueAsString(map);
                        resp.getWriter().write(s);
                        resp.getWriter().flush();
                        resp.getWriter().close();
                    }
                })
                .and()
                .authorizeRequests() //请求授权
                .antMatchers("/api/public/**","/").permitAll()
//                .antMatchers("/api/comment/**").hasAuthority("P")
//                .antMatchers("/api/type/**").hasAuthority("G")
                .anyRequest().authenticated()//任何请求 需要 登录
                .and()
                .logout()
                .logoutUrl("/logout").clearAuthentication(true).invalidateHttpSession(true)
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request,
                                       HttpServletResponse response,
                                       Authentication authentication) {

                    }
                })
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req,
                                                HttpServletResponse resp,
                                                Authentication authentication) throws IOException, ServletException {
                        Map map = new HashMap();
                        map.put("action","/api/public/goIndex");
                        String s = objectMapper.writeValueAsString(map);
                        resp.getWriter().write(s);
                        resp.getWriter().flush();
                        resp.getWriter().close();
                    }
                })
                .and()
                .csrf().disable(); // 禁止跨域
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
